package com.h2cloud;

import lombok.Data;
import lombok.experimental.Accessors;
import org.junit.platform.commons.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Callable;

/**
 * @author: wulongkai
 * @create: 2022-11-30 11:53
 **/
public class condition {
    public static void main(String[] args) {
        condition cond = new condition();

        boolean autoTrigger = false;
        boolean isHandUp = false;
        boolean isShow = true;
        String role = "role1";

        conditionArgs conditionArgs = new conditionArgs()
                .setAutoTrigger(autoTrigger)
                .setHandUp(isHandUp)
                .setShow(isShow)
                .setRole(role);

        try {
            conditionArgs
                    .add(condition.conditionArgs.CON1, () -> {
                        System.out.println("if");
                        return null;
                    })
                    .add(condition.conditionArgs.CON2, () -> {
                        System.out.println("else if");
                        return null;
                    });
            conditionArgs.excute();
        } catch (Exception e) {

        }
    }

    @Data
    @Accessors(chain = true)
    static class conditionArgs {
        boolean autoTrigger;
        boolean isHandUp;
        boolean isShow;
        String role;


        static String CON1 = "con1";
        static String CON2 = "con2";

        Map<String, Callable> conditionMap = new TreeMap<>();
        Map<String, Callable> funMap = new HashMap<>();

        public void excute() throws Exception {
            this.init();
            conditionMap.entrySet().forEach(e -> {
                try {
                    if (excuteCondition(e.getValue())) {
                        funMap.get(e.getKey()).call();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            });
        }

        public boolean excuteCondition(Callable callable) throws Exception {
            return (boolean) callable.call();
        }

        public void init() {
            conditionMap.put(CON1, () -> {
                if (autoTrigger || (isHandUp && !isShow)) {
                    return true;
                }
                return false;
            });

            conditionMap.put(CON2, () -> {
                if (StringUtils.isNotBlank(role)) {
                    return true;
                }
                return false;
            });
        }

        public conditionArgs add(String cond, Callable funCall) {
            funMap.put(cond, funCall);
            return this;
        }
    }
}
